﻿var GTPESign = {};
GTPESign._obj = null;

GTPESign.PluginInstalled = false;
GTPESign.AutoShowInstallBar = true;
GTPESign.Ready = false;
GTPESign.Version = "1.0";

GTPESign._delCookie = function (name) { //为了删除指定名称的cookie，可以将其过期时间设定为一个过去的时间
    var date = new Date();
    date.setTime(date.getTime() - 10000);
    document.cookie = name + "=a; expires=" + date.toGMTString();
};

GTPESign._getCookie = function (name) {
    var strCookie = document.cookie;
    var arrCookie = strCookie.split("; ");
    for (var i = 0; i < arrCookie.length; i++) {
        var arr = arrCookie[i].split("=");
        if (arr[0] == name)
            return arr[1];
    }
    return "";
};

GTPESign._encodePostData = function (str) { //为了删除指定名称的cookie，可以将其过期时间设定为一个过去的时间
    return encodeURIComponent(str);
};

GTPESign._xmlDocumentFromString = function (xmlString) {
    var xmlDom = null;
    if (window.ActiveXObject) {
        xmlDom = new ActiveXObject("Microsoft.XMLDOM");
        if (xmlDom) xmlDom.loadXML(xmlString);
    }
    else {
        xmlDom = new DOMParser().parseFromString(xmlString, "application/xml");
    }
    return xmlDom;
};

GTPESign._hashCode = function (s) {
    var h = 0, i, l = s.length
    for (i = 0; i < l; i++) {
        h = 31 * h + s.charCodeAt(i)
        if (h > 4294967296) h = h % 4294967296
    }
    if (h > 2147483648) h -= 4294967296
    return h
};

GTPESign._ajaxSyncCall = function (urlStr, paramsStr) {
    var obj;
    var value;
    if (window.ActiveXObject) {
        obj = new ActiveXObject('Microsoft.XMLHTTP');
    } else if (window.XMLHttpRequest) {
        obj = new XMLHttpRequest();
    }
    obj.open('POST', urlStr, false);
    obj.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    obj.send(paramsStr);
    return obj.responseText;
};

//由于相互间调用关系约束，以下方法的先后顺序不能变 **********************************************
GTPESign._getLocationRootDir = function () {
    //通过比较当前脚本的相对路径设置和当前页面的链接，得到当前的网站的根目录        
    var theCurJsFile_Short = "js/GTPESign.js".toLowerCase();
    var theCurJsFile = ("/" + theCurJsFile_Short).toLowerCase();

    var currentPageUrl = location.href;

    //fireFox 不支持 document.scripts
    var js = document.getElementsByTagName("script");
    var jsPath;
    for (var i = js.length; i > 0; i--) {
        jsPath = js[i - 1].src;
        if (jsPath.toLowerCase().indexOf(theCurJsFile) > -1) {
            return jsPath.substring(0, jsPath.toLowerCase().lastIndexOf(theCurJsFile))
        }
        else if (jsPath.toLowerCase() == theCurJsFile_Short) {
            return "../../";
        }
    }
    return "";
};

GTPESign._createPluginObject = function () {
    var objId = document.getElementById("div_GTPBrowserPluginObject");
    if (objId) {
        setTimeout(GTPESign._elementToObject, 50);
        return;
    }

    var html;
    if (window.ActiveXObject) {
        //IE 浏览器 ActiveX
        html = '<object classid=clsid:1141509E-F393-4710-95B1-86818A2E46FF ' +
            'style="display:none;height:0px;width:0px" id="GTPBrowserPluginObject" />';
    }
    else {
        //mozilla 系列浏览器支持的插件
        html = '<embed width="0px" height="0px" type="application/x-glodon-geps-client-plugin" ' +
             'data="data:application/x-glodon-geps-client-plugin" id="GTPBrowserPluginObject" />';
    }

    var o = document.body;

    //创建DIV
    var div = document.createElement("div");
    //不能设置 div 对象隐藏，否则 getElementById 得不到对象 
    div.setAttribute('style', 'position:absolute;left:0;top:0;width:0;height:0;z-index:100000000');
    div.setAttribute('id', 'div_GTPBrowserPluginObject');
    div.innerHTML = html;
    o.appendChild(div);

    //注意需要创建插件对象后延迟一段时间再检查插件是否已安装，留给浏览器加载插件的时间
    setTimeout(GTPESign._elementToObject, 50);
};

String.prototype.endWith = function (oString) {
    var reg = new RegExp(oString + "$");
    return reg.test(this);
};

GTPESign._displayInstallBar = function () {
    if (!GTPESign.AutoShowInstallBar) return;

    var tbl = document.getElementById("div_tblGTPBrowserPluginInstallBar");
    if (tbl) {
        tbl.style.display = "block";
        return;
    }

    var rootUrl = this._getLocationRootDir();
    if (!rootUrl.endWith("/")) {
        rootUrl += "/";
    }
    var closeImgSrc = rootUrl + "images/cross.png";
    var installPage = rootUrl + "installPluginIE.htm";
    if (!window.ActiveXObject)
        installPage = rootUrl + "installPluginFF.htm";
    var hint;

    //if (GTPESign._langID == 2052)//TODO：真正支持多语言
        hint = "需安装安全登录组件(v" + GTPESign.Version + ")以支持此页面的功能，请先卸载已有组件后重新安装。";
//    else if (GTPESign._langID == 1028)
//        hint = "需安裝數字簽名組件(v" + GTPESign.Version + ")以支持此页面的功能，請先卸載已有組件後重新安裝。";
//    else
//        hint = "A ESignature component(v" + GTPESign.Version + ") is need to be installed for this page, click here to reinstall.";

    var html =
    "<table id=\"tblGTPBrowserPluginInstallBar\" style=\"border: 1px solid #C0C0C0; padding: 10px; position: absolute; width: 100%;" +
    "left: 0px; top: 0px; height: 30px; background-color: #FFCC00; cursor: pointer\"><tr>" +
    "<td onclick=\"javascript:window.open('" + installPage + "');\">" +
    "<font size=\"2\">&nbsp;&nbsp;" + hint + "</font></td>" +
    "<td width=\"30\" align=\"center\">" +
    "<img src=\"" + closeImgSrc + "\" " +
    "onclick=\"javascript:document.getElementById('div_tblGTPBrowserPluginInstallBar').style.display='none';\" />" +
     "</td></tr></table>";

    var o = document.body;
    var div = document.createElement("div");
    div.setAttribute("id", "div_tblGTPBrowserPluginInstallBar");
    div.setAttribute('style', 'z-index:10000000');

    div.innerHTML = html;
    o.appendChild(div);
};

GTPESign._checkPluginInstalled = function () {
    GTPESign._obj = document.getElementById("GTPBrowserPluginObject");

    GTPESign.PluginInstalled = GTPESign._getPluginInstalled();
    if (!GTPESign.PluginInstalled) {
        //仅在对象被调用时判断
        GTPESign._displayInstallBar();  //在页面顶部显示安装提示    
    }

    GTPESign.Ready = true;
    if (GTPESign.OnReady) {
        GTPESign.OnReady();
        GTPESign.OnReady = null;
    }
};

GTPESign._elementToObject = function () {
    GTPESign._obj = document.getElementById("GTPBrowserPluginObject");
    GTPESign._delCookie(GTPESign._cookieName);
    setTimeout(GTPESign._checkPluginInstalled, 100);
};

GTPESign._processPageOnload = function () {
//    if (window.removeEventListener)
//        window.removeEventListener('load', GTPESign._processPageOnload, false);
//    else
//        window.detachEvent('onload', GTPESign._processPageOnload);

    var rootUrl = GTPESign._getLocationRootDir();
    if (!rootUrl.endWith("/"))
        rootUrl += "/";

    //页面加载完成后，尝试在页面插入隐藏的ActiveX 或者 NPAPI插件 Object 
    //注意需要延迟一段时间，否则FireFox 可能由于div对象过多导致
    setTimeout(GTPESign._createPluginObject, 50);
};

//*************************************************************************

//由于相互间调用关系约束，以上方法的先后顺序不能变 **********************************************

//ActiveX 方法 Begin *************************************************************************


GTPESign._ES_Encrypt = function (encryptResult, esFlags) {

    if (undefined == esFlags)
        esFlags = "0";
    if (undefined == encryptResult)
        encryptResult = "";
    var resultStr = this._obj.ES_Encrypt(encryptResult, esFlags);
    return resultStr;

};


//ActiveX 方法 End *************************************************************************

GTPESign._getPluginInstalled = function () {
    var installed = false;
    if (this._obj) {
        try {
            // 如果版本不同都提示需要重新安装
            if (this._obj.ES_Version() == GTPESign.Version)
                installed = true;
        }
        catch (e) {
            //alert(e);
        }
    }
    return installed;
};

//公开接口 begin ***************************************************************************************************************


GTPESign.Encrypt = function (encryptResult) {

    var signResult = GTPESign._ES_Encrypt(encryptResult, 0);
    return signResult;

};

GTPESign.Load = function (onReady) {
    GTPESign._processPageOnload();
    GTPESign.OnReady = onReady;
};

//公开接口 end ***************************************************************************************************************